#!/usr/bin/env python
#coding=utf-8

import os
import re
import hashlib
import uuid
import time
import Image
from datetime import datetime
from datetime import date
from threading import Thread

from flask import current_app, g
from flask.ext.mail import Message
from .extensions import db, mail, cache, photos

WEATHER_API = "http://sou.qq.com/online/get_weather.php?city="


_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
_pre_re = re.compile(r'<pre (?=l=[\'"]?\w+[\'"]?).*?>(?P<code>[\w\W]+?)</pre>')
_lang_re = re.compile(r'l=[\'"]?(?P<lang>\w+)[\'"]?')


def slugify(text, delim=u'-'):
    """Generates an ASCII-only slug. From http://flask.pocoo.org/snippets/5/"""
    result = []
    for word in _punct_re.split(text.lower()):
        #word = word.encode('translit/long')
        if word:
            result.append(word)
    return unicode(delim.join(result))


def format_timestamp(timestamp):
    t_tuple = time.localtime(timestamp)
    dt = datetime(*t_tuple[:6])
    return dt.strftime("%Y-%m-%d %H:%M:%S")


def get_photo_path_name():
    random_str = hashlib.md5(str(uuid.uuid1())).hexdigest()
    return ('%s/%s' % (random_str[0:2], random_str[2:4]), random_str[4:])


def save_image(data, kind=None, name=None):
    photo_path, photo_name = get_photo_path_name()
    name = name if name else photo_name
    path = '%s/%s' % (kind, photo_path) if kind else photo_path
    photoname = photos.save(data, folder=path, name='%s.' % name)
    extension_name = photoname.split('.')[1]
    # photo = Image(name=name, path=photo_path, extension_name=extension_name)
    # db.session.add(photo)
    # db.session.commit()

    return photoname.split(kind+'/')[1] if kind else photoname


def resize_image(path, sizes):
    """
    sizes 参数传递要生成的尺寸，可以生成多种尺寸
    """
    if not sizes:
        sizes = [(48,48)]
    base, ext = os.path.splitext(path)
    print path
    try:
        im = Image.open(path)
        im.load()
    except IOError:
        print ' in  IOError'
        return
    mode = im.mode
    if mode not in ('L', 'RGB'):
        if mode == 'RGBA':
            # 透明图片需要加白色底
            alpha = im.split()[3]
            bgmask = alpha.point(lambda x: 255-x)
            im = im.convert('RGB')
            # paste(color, box, mask)
            im.paste((255,255,255), None, bgmask)
        else:
            im = im.convert('RGB')

    width, height = im.size
    # images_dict = {}
    for size in sizes:
        if size[0] == 0:
            thumb = im.resize((width/(height/size[1]), size[1]), Image.ANTIALIAS)
        elif size[1] == 0:
            thumb = im.resize((size[0], height/(width/size[0])), Image.ANTIALIAS)
        else:
            if width == height:
                region = im
            else:
                if width/height > size[0]/size[1]:
                    new_width = size[0]*height/size[1]
                    new_height = height
                else:
                    new_width = width
                    new_height = size[1]*width/size[0]

                if new_height != height:
                    delta = (height - new_height)/2
                    box = (delta, 0, new_width, new_height+delta)
                else:
                    delta = (width - new_width)/2
                    box = (0, delta, new_width+delta, new_height)
                region = im.crop(box)

            thumb = region.resize((size[0],size[1]), Image.ANTIALIAS)

        filename = base + "_" + "%s_%s" % (str(size[0]), str(size[1])) + "." + path.split('.')[-1]
        # print filename
        thumb.save(filename, quality=100) # 默认 JPEG 保存质量是 75, 不太清楚。可选值(0~100)
        # images_dict['%s_%s' % (str(size[0]), str(size[1]))] = filename
    # return images_dict


def async(f):
    def wrapper(*args, **kwargs):
        thr = Thread(target=f, args=args, kwargs=kwargs)
        thr.start()
    return wrapper


# @async
def send_async_email(msg):
    mail.send(msg)


def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender = sender, recipients = recipients)
    msg.body = text_body
    msg.html = html_body
    # send_async_email(msg)
    thr = Thread(target = send_async_email, args = [msg])
    thr.start()


import multiprocessing

def processing_pool(f):
    def wrapper(*args, **kwargs):
        pool = multiprocessing.Pool(processes=4)
        pool.apply_async(f, (args, kwargs))
        pool.close()
        pool.join()
    return wrapper

def send_async_mail(msg):
    mail.send(msg)

def send_mail(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender = sender, recipients = recipients)
    msg.body = text_body
    msg.html = html_body

    pool = multiprocessing.Pool(processes=4)
    pool.apply_async(send_async_mail, (msg, ))
    pool.close()
    pool.join()
